import type { AudDialogShowParams } from '@/pages/components/Aud/AudDialog';
import { Popup, SelectBox, TextBox, } from 'devextreme-react';
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef } from 'react';
import { useState } from 'react';
import { handleStr, intl } from '@/utils';
import { useModel } from 'umi';
import Form, { Item } from 'devextreme-react/form';
import { CpasIcon } from '~/public/cpas-ui';
import "./index.less"
// import CarryEntryPopup from '~/public/cpas-business/components-bs/CarryEntryPopup';
import SubjectPopups from "~/public/cpas-business/components-bs/SubjectPopup"
import { updateJZKM } from '../../service';
import notify from 'devextreme/ui/notify';

// import validationEngine from "devextreme/ui/validation_engine";

// import Validator, { RequiredRule } from 'devextreme-react/validator';


import {
    Validator,
    RequiredRule,
} from 'devextreme-react/validator';

import validationEngine from "devextreme/ui/validation_engine";

export interface SizeProp {
    width?: number | string,
    height?: number | string,
}

// 编辑界面

const EntryPopup: React.FC<any> = React.forwardRef((props: any, ref) => {
    const { initialState } = useModel('@@initialState');
    const { dbname } = initialState?.curPart as API.CurPart;
    const { username } = initialState?.curUser as API.CurUser;
    const { setIsShowGlobalLoad } = useModel('useAdjustModel');

    const { width, height, AccountDataID } = props;
    const refsForm = useRef<any>();

    const diaParams = useRef<AudDialogShowParams>();
    const SubjectRef = useRef<any>();
    // const CarryEntryPopupRef = useRef<any>();

    const [visible, setVisible] = useState<boolean>(false);
    const [size, setSize] = useState<SizeProp>({ width, height });
    const [formAllData, setFormAllData] = useState<any>({
        QCJZKMMC: "",
        QCJZKM: "",
        QMJZKMMC: "",
        QMJZKM: "",
        YQSYKMMC: "",
        YQSYKM: "",
    });
    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: async (params: AudDialogShowParams & any) => {
            diaParams.current = params;
            if (diaParams.current?.args?.data) {
                setFormAllData(diaParams.current?.args?.data);
            } else {
                setFormAllData({
                    QCJZKMMC: "",
                    QCJZKM: "",
                    QMJZKMMC: "",
                    QMJZKM: "",
                    YQSYKMMC: "",
                    YQSYKM: "",
                });
            }
            setVisible(true);
        },
        close: () => { setVisible(false) }
    }));

    const onOk = useCallback(async () => {
        // let validationResult = validationEngine.validateGroup("formGroup");
        console.log(formAllData, '@@@');
        if (formAllData.QCJZKM && formAllData.QMJZKM) {
            if (diaParams.current?.okCallback) {
                const r = await updateJZKM({
                    dbname,
                    Data_ID: AccountDataID,
                    editUser: username,
                    QCJZKM: formAllData.QCJZKM,
                    QMJZKM: formAllData.QMJZKM,
                    YQSYKM: formAllData.YQSYKM
                })
                if (r) {
                    setVisible(false);
                    notify('设置结转科目成功', 'success', 2000)
                }
                diaParams.current?.okCallback();
            }
        } else {
            notify('请设置必填项的结转科目', 'warning', 2000)
        }
    }, [formAllData])



    const onCancel = () => {
        setVisible(false);
        setIsShowGlobalLoad(false);
        if (diaParams.current?.args.tipNotify) {
            notify("未设置结转科目，无法自动生成结转分录，请手动结转！", 'error', 2000);
        }
    }





    const lastNameRender = () => {
        return (<>
            <TextBox
                value={formAllData.QCJZKMMC}
                valueChangeEvent='keyup'
                readOnly={true}
                showClearButton={true}
            >
                {/* // <TextBox defaultValue={this.state.employee.LastName} onValueChanged={valueChanged}> */}
                <Validator validationGroup="formGroup">
                    <RequiredRule message="期初结转科目必填" />
                </Validator>
            </TextBox>

            <span style={{ position: 'absolute', right: '6px', top: "6px" }}>
                <CpasIcon type="icon-xinzengkemu" onClick={() => {
                    SubjectRef.current.show({
                        title: "选择科目",
                        dbname: dbname,
                        Data_ID: AccountDataID,
                        isHasFZZ: false,
                        editUser: username,
                        // 选择 模式 0：单选 1：多选连机选择
                        selectMode: '0',
                        // 是否为辅助账 
                        auxiliaryState: false,
                        // 是否可以选择上级科目
                        isSelectSuperior: false,
                        subjectType: "periodEarly",
                        okCallback: (r: any, v: any) => {
                            // 科目审定明细 界面增加一级科目在业务组件 需做更改
                            setFormAllData((oldData: any) => ({
                                ...oldData,
                                QCJZKMMC: r.displayName,
                                QCJZKM: r.ID
                            }));
                            //  setPeriodName(r.displayName);
                            // setPeriodNameKey(r.ID);
                        },
                    });
                }} />
            </span>
        </>
        );
    }



    const lastNameRender2 = () => {
        return (<>
            <TextBox
                value={formAllData.QMJZKMMC}
                valueChangeEvent='keyup'
                readOnly={true}
                showClearButton={true}
            >
                <Validator validationGroup="formGroup">
                    <RequiredRule message="期末结转科目必填" />
                </Validator>
            </TextBox>

            <span style={{ position: 'absolute', right: '6px', top: "6px" }}>
                <CpasIcon type="icon-xinzengkemu" onClick={() => {
                    SubjectRef.current.show({
                        title: "选择科目",
                        dbname: dbname,
                        Data_ID: AccountDataID,
                        isHasFZZ: false,
                        editUser: username,
                        // 选择 模式 0：单选 1：多选连机选择
                        selectMode: '0',
                        // 是否为辅助账 
                        auxiliaryState: false,
                        // 是否可以选择上级科目
                        isSelectSuperior: false,
                        subjectType: "periodEarly",
                        okCallback: (r: any, v: any) => {
                            // 科目审定明细 界面增加一级科目在业务组件 需做更改
                            setFormAllData((oldData: any) => ({
                                ...oldData,
                                QMJZKMMC: r.displayName,
                                QMJZKM: r.ID
                            }));
                            //  setPeriodName(r.displayName);
                            // setPeriodNameKey(r.ID);
                        },
                    });
                }} />
            </span>
        </>
        );
    }

    return (
        <>
            <Popup
                ref={ref}
                visible={visible}
                title={diaParams.current?.args?.title}
                minWidth={500}
                minHeight={280}
                {...props}
                {...size}
                // dragOutsideBoundary={true}
                resizeEnabled={true}
                onHiding={() => {
                    onCancel();
                }}
                toolbarItems={[
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => onCancel()
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => onOk()
                        },
                    },
                ]}
                onResizeEnd={(e) => {
                    setSize({ width: e.width, height: e.height });
                }}
            // contentRender={() => (

            // )}
            >
                <Form
                    ref={refsForm}
                    colCount={1}
                    formData={formAllData}
                    className='SubjectsForm'
                    focusStateEnabled={true}
                    showColonAfterLabel={true}
                    alignItemLabels={true}
                    validationGroup="formGroup"
                >
                    <Item dataField="QCJZKMMC" label={{ text: '期初结转科目' }} isRequired={true}
                        render={lastNameRender} />

                    <Item dataField="QMJZKMMC" label={{ text: '期末结转科目' }} isRequired={true}
                        render={lastNameRender2} />
                    <Item
                        dataField="YQSYKMMC"
                        label={{ text: '以前年度损益科目' }} >
                        <TextBox
                            value={formAllData.YQSYKMMC}
                            valueChangeEvent='keyup'
                            readOnly={true}
                            showClearButton={true}
                        />
                        <span style={{ position: 'absolute', right: '6px', top: "6px" }}>
                            <CpasIcon type="icon-xinzengkemu" onClick={() => {
                                SubjectRef.current.show({
                                    title: "选择科目",
                                    dbname: dbname,
                                    Data_ID: AccountDataID,
                                    isHasFZZ: false,
                                    editUser: username,
                                    // 选择 模式 0：单选 1：多选连机选择
                                    selectMode: '0',
                                    // 是否为辅助账 
                                    auxiliaryState: false,
                                    // 是否可以选择上级科目
                                    isSelectSuperior: false,
                                    subjectType: formAllData.YQSYKMMC ? '' : "periodProfit",
                                    okCallback: (r: any, v: any) => {
                                        // 科目审定明细 界面增加一级科目在业务组件 需做更改
                                        console.log(r, v, 'r-------sssssssss----------');
                                        setFormAllData((oldData: any) => ({
                                            ...oldData,
                                            YQSYKMMC: r.displayName,
                                            YQSYKM: r.ID
                                        }));
                                        //  setYqsykmmc(r.displayName);
                                        // setYqsykmmcKey(r.ID)
                                    },
                                });
                            }} />
                            <CpasIcon type="icon-close1" onClick={() => {
                                // setYqsykmmc('');
                                setFormAllData((oldData: any) => ({
                                    ...oldData,
                                    YQSYKMMC: "",
                                    YQSYKM: ""
                                }));
                            }} />
                        </span>
                    </Item>
                </Form>
                <SubjectPopups ref={SubjectRef} />

            </Popup>
        </>
    );
});


export default React.memo(EntryPopup);